import { ref, reactive, shallowRef } from 'vue'
import * as echarts from 'echarts'
import getInitOption from '../options/FlowOption'
import { getColor } from '../utils/colorUtils'

const chartInstance = shallowRef() // 图表实例
const allFlowData = reactive([]) // 数据
const maxScale = ref(30) // 最大显示点数
const config = ref({ max: 35000, min: 0 }) // 图表配置
const titleFontSize = ref(0) // 图表字体大小
const flowRef = shallowRef()

function registerFlow(flow) {
  flowRef.value = flow
}
function initChart() {
  chartInstance.value = echarts.init(flowRef.value, 'dark')
  chartInstance.value.setOption(getInitOption(config.value))
}
function screenAdapter() {
  titleFontSize.value = (flowRef.value.offsetWidth / 100) * 2.5
  const apdaterOption = {
    xAxis: {
      nameTextStyle: {
        fontSize: titleFontSize.value
      }
    },
    yAxis: {
      nameTextStyle: {
        fontSize: titleFontSize.value
      }
    }
  }
  chartInstance.value.setOption(apdaterOption)
  chartInstance.value.resize()
}
function updateFlow(time, data, status) {
  const flowData = {
    name: time,
    value: [time, data],
    itemStyle: {
      color: status === 1 ? getColor(1) : getColor(0),
      borderRadius: [titleFontSize.value, titleFontSize.value, 0, 0]
    }
  }
  allFlowData.push(flowData)
  while (allFlowData.length > maxScale.value) {
    allFlowData.shift()
  }
  updateFlowChart()
}
function updateFlowChart() {
  const dataOption = {
    series: [
      {
        data: allFlowData
      }
    ]
  }
  chartInstance.value.setOption(dataOption)
}
function clearAllFlowData() {
  allFlowData.splice(0, allFlowData.length)
  updateFlowChart()
}

export const useFlow = () => {
  return {
    registerFlow,
    initChart,
    screenAdapter,
    updateFlow,
    clearAllFlowData
  }
}
